package com.ruoyi.tools.util.time;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class TimeUtil {
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        List<String> list = null;
        try {
            list = findDates("N", "09:00", "15:00",30);
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (String str :list){
            System.out.println(str);
        }
    }
    /**
     * 按照指定小时分割时间段
     * @param dateType 类型 M/D/H/N -->每月/每天/每小时/每分钟
     * @param dBegin开始时间
     * @param dEnd结束时间
     * @param time 指定小时(如：1、2、3、4)
     * @return
     */
    public static List<String> findDates(String dateType, String startDate, String endDate, int time) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date dBegin = sdf.parse("2021-05-07".concat(" "+startDate+""));
        Date dEnd = sdf.parse("2021-05-07".concat(" "+endDate+""));

        List<String> listDate = new ArrayList<>();
        listDate.add(new SimpleDateFormat("HH:mm").format(dBegin));
        Calendar calBegin = Calendar.getInstance();
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        calEnd.setTime(dEnd);
        while (calEnd.after(calBegin)) {
            if ("H".equals(dateType)){
                calBegin.add(Calendar.HOUR, time);
            }
            if ("M".equals(dateType)){
                calBegin.add(Calendar.MONTH, time);
            }
            if ("D".equals(dateType)){
                calBegin.add(Calendar.DATE, time);
            }
            if ("N".equals(dateType)){
                calBegin.add(Calendar.MINUTE , time);
            }
            if (calEnd.after(calBegin)){
                listDate.add(new SimpleDateFormat("HH:mm").format(calBegin.getTime()));
            }
            else{
                listDate.add(new SimpleDateFormat("HH:mm").format(calEnd.getTime()));
            }

        }

        return listDate;
    }


    //判断第一个时间是否在第二个时间之前
    public static boolean isFirstTimeBeforeSecondTime(String time1, String time2) {
        LocalTime localTime1 = LocalTime.parse(time1);
        LocalTime localTime2 = LocalTime.parse(time2);

        return localTime1.isBefore(localTime2);
    }

    //计算开始时间加上指定时间后的结果
    public static String addMinutesToStartTime(String startTime, int minutesToAdd) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
        LocalTime startTimeObj = LocalTime.parse(startTime, formatter);
        LocalTime endTimeObj = startTimeObj.plusMinutes(minutesToAdd);
        return endTimeObj.format(formatter);
    }
}
